/**
 * 公共工具集
 * @author wqhui
 */
define(function(require, exports, module) {
	/**
	 * 支持debug的标志
	 */
	var debugEnable = true;
	module.exports = {
		/**
		 * debug:在控制台中打印日志
		 */
		debug : function(msg) {
			if (!debugEnable) {
				return;
			}
			try {
				console.log(msg);
			} catch (e) {
				// INGNORE
			};
		},

		/**
		 * enableDebug:设置是否允许在控制台中的打印
		 */
		enableDebug : function(enable) {
			debugEnable = enable;
		},

		/**
		 * getContextPath:获取当前应用的contextPath
		 */
		getContextPath : function() {
			var tmpPathName = document.location.pathname;
			tmpPathName = tmpPathName.substring(1);
			var iPos = tmpPathName.indexOf('/');
			var contextPath = tmpPathName.substring(0, iPos);
			return '/' + contextPath;
		},

        GetUrlRelativePath:function() {
            var url = document.location.toString();
            var arrUrl = url.split("//");

            var start = arrUrl[1].indexOf("/");
            var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

            //        if(relUrl.indexOf("?") != -1){
            //            relUrl = relUrl.split("?")[0];
            //        }
            return relUrl;
        },

        cookie : function(name, value, options) {
            if (typeof value != 'undefined') { // name and value given, set cookie
                options = options || {};
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                var path = options.path ? '; path=' + options.path : '';
                var domain = options.domain ? '; domain=' + options.domain : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else { // only name given, get cookie
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },

		/**
		 * getBlankPage:Https协议下获取空白页面，页面位置：/resources/blank.htm
		 */
		getBlankPage : function() {
			try {
				var protocolObj = document.location.protocol;
				if (protocolObj != null && protocolObj.toUpperCase().indexOf("HTTP") != 0) {
					return "";
				}
			} catch (e) {
				this.debug(e.message);
			}
			var contextPath = getContextPath();
			return contextPath + '/resources/blank.htm';
		},

		/**
		 * ajax : 默认使用json格式的ajax调用
		 */
		ajax : function(postUrl, postData, successFunc, async, errorFunc,
				beforeSendFunc, completeFunc, jsonp, extendSettings) {
			var _this = this;
			var settings =  {
                type : 'POST',
                global : false,
                dataType : 'json',
                url : postUrl,
                data : postData,
                async : (typeof(async) === 'undefined' || async),

                success : function(data) {
                    if (!data.success && data.errorcode == 'ETS-5BP00001') { // 登录超时
                        window.top.location = (_this.getContextPath() + '/timeout');
                        return;
                    }
                    return successFunc(data);
                }
			};
			
			// 如果errorFunc不是function，则认为就是Jsonp的参数
			if(!$.isFunction(errorFunc)&&errorFunc!=null) {
				jsonp = errorFunc;
			} else {
				settings = $.extend(settings, {
					beforeSend : beforeSendFunc,
					error : errorFunc,
					complete : completeFunc
				});
			}
			
			if(jsonp) {
				settings = $.extend(settings, {dataType : 'jsonp', jsonp : 'jscallback'});
			}
			
			if(extendSettings) {
				settings = $.extend(settings, extendSettings);
			}

            settings = $.extend(settings, {abortOnRetry : true});
			$.ajax(settings);
		},

        // 自动有浮层，同步请求
        simpleAjax : function(url, data, succFunc, errorFunc) {
            var _this = this;
            var settings =  {
                type : "POST",
                global : true,
                dataType : "json",
                url : url,
                data : data,
                async : true,
                abortOnRetry : true,

                success : function(data) {
                    if (!data.success && data.errorcode == 'ETS-5BP00001') { // 登录超时
                        window.top.location = (_this.getContextPath() + '/timeout');
                        return;
                    }
                    if($.isFunction(succFunc)) {
                        return succFunc(data);
                    }
                }
            };

            if($.isFunction(errorFunc)) {
                settings = $.extend(settings, {
                    error : errorFunc
                });
            }

            $.ajax(settings);
        },

        PostPage : function(url, args, newWinFlag) { // post提交数据，可新开页面
            var body = $(document.body);
            var form = $("<form method='post'"+(newWinFlag==true ? " target='_blank'" : "")+"></form>");
            form.attr({"action":url});
            $.each(args,function(key,value){
                if(value instanceof Array) {
                    for(var index=0; index<value.length; ++index) {
                        var input = $("<input type='hidden'>");
                        input.attr({"name":key});
                        input.val(value[index]);
                        form.append(input);
                    }
                }
                else {
                    var input = $("<input type='hidden'>");
                    input.attr({"name":key});
                    input.val(value);
                    form.append(input);
                }
            });
            form.appendTo(document.body);
            form.submit();
            document.body.removeChild(form[0]);
        },

        loadHtml : function(url, callback) {
            $.ajax({
                url: url,
                type: "GET",
                dataType : "html",
                global : false,
                success: function(data){
                    if(typeof(callback) == "function") {
                        callback(data);
                        return;
                    }

                    if($("#loadhtml_template").length == 0) {
                        $(document.body).append('<div id="loadhtml_template"></div>');
                    }

                    $("#loadhtml_template").html(data);
                }
            });
        },

		/**
		 * generUrl对Url增加Token处理
		 */
		generUrl : function(returnURL) {
			var tokenName = "SECURE_TOKEN";
			if (returnURL != null && returnURL != "") { // returnURL
				var index = returnURL.indexOf('?');
				var index2 = returnURL.indexOf('#');

				if (index != -1) {
					if (index2 != -1) {
						returnURL = returnURL.substring(0, index2) + '&' + tokenName + '=' + $hs_secure_token + returnURL.substring(index2, returnURL.length);
					} else {
						returnURL = returnURL + '&' + tokenName + '=' + $hs_secure_token;
					}
				} else {
					if (index2 != -1) {
						returnURL = returnURL.substring(0, index2) + '?' + tokenName + '=' + $hs_secure_token + returnURL.substring(index2, returnURL.length);
					} else {
						returnURL = returnURL + '?' + tokenName + '=' + $hs_secure_token;
					}
				}
			}
			return returnURL;
		},
		
		/**
		 * 得到光标的位置，obj为控件对象，支持文本域和输入框
		 * 
		 * @param obj 输入框的DOM对象
		 * @returns {Number}
		 */
		getPosition : function(obj) {
			var result = 0;
			try {
				if (obj.selectionStart) { // 非IE浏览器
					result = obj.selectionStart;
				} else { // IE
					var rng;
					if (obj.tagName == "TEXTAREA") { // 如果是文本域
						rng = event.srcElement.createTextRange();
						rng.moveToPoint(event.x, event.y);

						rng.moveStart("character", -event.srcElement.value.length);
						result = rng.text.length;
					} else { // 输入框
						if (document.selection) {
							rng = document.selection.createRange();
							rng.moveStart("character", -document.selection.createRange().text.length);
							result = rng.text.length;
						}
					}
				}
			} catch (e) {
			}
			return result;
		},
		
		logout : function() {
			var _this = module.exports;
            $.confirm("您确定退出吗？", function() {
                top.window.location = _this.getContextPath() + '/account/login/logout';
            });
            _paq.push(['trackEvent', Piwik_Event_Quota.login.category, Piwik_Event_Quota.login.logout.action,'']); // 页面需要已经加载piwik.js
		},
		
		//预览页面点击返回按钮，返回表单填写页面，并保留客户原有表单信息
		returnToInit : function(initURL) {
			var _this = module.exports;
			document.forms[0].target='_self';
			document.forms[0].action=_this.getContextPath() + initURL;
			document.forms[0].submit();
		},
		
        //判断浏览器是否支持cookie
		cookieEnable : function () {
            if (window.navigator.cookieEnabled) {
                return true;
            }

            var result = false;
            window.document.cookie = "testcookie=yes;";
            var cookieSet = window.document.cookie;
            if (cookieSet.indexOf("testcookie=yes") > -1) {
                result = true;
            }

            //删除测试的cookie
            var exp = new Date();
            exp.setTime(exp.getTime() - 10000);
            window.document.cookie = "testcookie=yes; expires=" + exp.toGMTString();
            return result;
        },
        
        //规范化url地址。如果是内部地址，则规范化路径。如果是外部地址，则不做任何处理。
        normUrl : function (url, addToken) {
        	var _this = module.exports;
    		var normUrl = url;
    		var outSideUrlSegmentReg = /^http/i;
    		
    		if(!outSideUrlSegmentReg.test(normUrl)) {
    			normUrl = _this.getContextPath() + normUrl;
    			//增加SECURE_TOKEN
    			if (typeof(addToken) === 'undefined' || addToken) {
    				normUrl =  _this.generUrl(normUrl); 
    			}
    		}
    		return normUrl;
    	},

        ///////////////////////////////////////////////////////////////////////
        // show tips
        toastObj : null,
        defaultTipTimeout : 3000,
         showErrorTip : function(msg, timeout) {
            var $this = this;
            seajs.use("jquery.toastmessage", function(obj) {
                obj.toastmessage('showErrorToast', msg, typeof(timeout) == "undefined" ? $this.defaultTipTimeout : timeout);
            });
        },

        showNoticeTip : function(msg, timeout) {
            var $this = this;
            seajs.use("jquery.toastmessage", function(obj) {
                obj.toastmessage('showNoticeToast', msg, typeof(timeout) == "undefined" ? $this.defaultTipTimeout : timeout);
            });
        },

        showSuccessTip : function(msg, timeout) {
            var $this = this;
            seajs.use("jquery.toastmessage", function(obj) {
                obj.toastmessage('showSuccessToast', msg, typeof(timeout) == "undefined" ? $this.defaultTipTimeout : timeout);
            });
        },

        showLoadingTip : function(msg, timeout) {
            var $this = this;
            seajs.use("jquery.toastmessage", function(obj) {
                $this.toastObj = obj.toastmessage('showLoadingToast', msg, typeof(timeout) == "undefined" ? $this.defaultTipTimeout : timeout);
            });
        },

        hideLoadingTip : function() {
        	var $this = this;
            seajs.use("jquery.toastmessage", function(obj) {
                obj.toastmessage('removeToast', $this.toastObj);
            });
        },
        

        ///////////////////////////////////////////////////////////////////////
        // show dialog
        showDialog : function(title, content, width, height, btn_options) {
            require("../../css/jquery-ui.css");
            seajs.use("jquery-ui", function() {
                if($("#popupDialog").length == 0) {
                    $(document.body).append('<div id="popupDialog" style="display: none;height:100%"></div>');
                }

                if(typeof(title) == "undefined" || title.length == 0) {
                    title = "　";
                }
                $("#popupDialog").html(content);
                $("#popupDialog").attr("title", title);
                $(".ui-dialog-title").text(title);

                var minWidth = 360;
                var minHeight = 180;
                var autoWidth = $("#popupDialog").width()+30;
                var autoHeight = $("#popupDialog").height();
                autoWidth = Math.max(minWidth, autoWidth);
                autoHeight = Math.max(minHeight, autoHeight);

                $("#popupDialog").dialog({
                    closeOnEscape:true,
                    resizable: false,
                    modal: true,
                    width: (typeof(width) != "undefined" && width > 0) ? width : autoWidth,
                    height: (typeof(height) != "undefined" && height > 0) ? height : "auto",
                    buttons: typeof(btn_options) != "undefined" ? btn_options : {
                        "确定": function() {
                            $(this).dialog("close");
                        }
                    }
                });
            });
        },
        isMobile : function(s) {
			return (/^(13|14|15|18|17|16|19)[0-9]{9}$/.test(s));        },

        fmtMoney : function(s, n) {
            n = n > 0 && n <= 20 ? n : 2;
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
            var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
            t = "";
            for (i = 0; i < l.length; i++) {
                t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
            }
            return t.split("").reverse().join("") + "." + r;
        }
	};
});
